import cv2
import numpy as np


def split_table_cells(image_path):
    # 1. 读取图像并预处理
    img = cv2.imread(image_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    binary = cv2.adaptiveThreshold(
        blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2
    )

    # 2. 检测直线
    edges = cv2.Canny(binary, 50, 150, apertureSize=3)
    lines = cv2.HoughLinesP(
        edges, 1, np.pi / 180, threshold=100, minLineLength=100, maxLineGap=10
    )

    # 3. 分离水平线和垂直线
    horizontal = []
    vertical = []
    for line in lines:
        x1, y1, x2, y2 = line[0]
        if abs(y2 - y1) < 10:  # 水平线
            horizontal.append(line[0])
        elif abs(x2 - x1) < 10:  # 垂直线
            vertical.append(line[0])

    # 4. 合并接近的线条
    def merge_lines(lines, threshold=10):
        lines_sorted = sorted(lines, key=lambda x: x[1])
        merged = [lines_sorted[0]]
        for line in lines_sorted[1:]:
            if abs(line[1] - merged[-1][1]) > threshold:
                merged.append(line)
        return merged

    horizontal = merge_lines(horizontal, threshold=15)
    vertical = merge_lines(vertical, threshold=15)

    # 5. 提取交点生成网格
    x_coords = sorted(list(set([v[0] for v in vertical])))
    y_coords = sorted(list(set([h[1] for h in horizontal])))

    # 6. 分割单元格
    cells = []
    for i in range(len(y_coords) - 1):
        for j in range(len(x_coords) - 1):
            x1, x2 = x_coords[j], x_coords[j + 1]
            y1, y2 = y_coords[i], y_coords[i + 1]
            cell = img[y1:y2, x1:x2]
            cells.append(cell)

    return cells

